package com.atguigu.oshiapp.oshiapp;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jna.platform.win32.WinUser;
import lombok.SneakyThrows;
import lombok.ToString;
import org.junit.Test;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.software.os.unix.aix.AixOperatingSystem;

import java.lang.runtime.ObjectMethods;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Mouoal
 * @CreateTime: 2025-01-06  16:59
 * @Version: 1.0
 */
public class OSHITest {

    //1、创建si对象
    SystemInfo si = new SystemInfo();


    @Test
    public void testCPU(){
        HardwareAbstractionLayer hardware = si.getHardware();

        //CentralProcessorUnit 拿到CPU
        CentralProcessor processor = hardware.getProcessor();

        //2、获取CPU最大频率
        long maxFreq = processor.getMaxFreq();

        System.out.println("最大频率=" + maxFreq);

        //3、获取CPU当前频率; 返回所有逻辑CPU当前频率
        long[] currentFreq = processor.getCurrentFreq();
        System.out.println("当前频率-"+ Arrays.toString(currentFreq));

        //当前频率/最大频率 = 当前CPU占用率


        //5、获取CPU 1s的使用情况
        double[] cpuLoad = processor.getProcessorCpuLoad(1000);
        System.out.println("cpuLoad = "+Arrays.toString(cpuLoad));

    }













    @SneakyThrows
    @Test
    public void testMemory() throws Exception,IllegalStateException{
        HardwareAbstractionLayer hardware = si.getHardware();
//每秒打印一次
        while (true) {

            Thread.sleep(1000);
            //获取内存信息
            GlobalMemory memory = hardware.getMemory();
//                ObjectMapper mapper = new ObjectMapper();
//                String string = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(memory);
//                System.out.println("==="+string);

            //获取可用内存
          System.out.println("可用内存====" + memory.getAvailable());
        }
    }

    @SneakyThrows
    @Test
    public void test01(){

        //2、获取操作系统对象
        OperatingSystem os = si.getOperatingSystem();

        //获取进程json信息
        ObjectMapper mapper = new ObjectMapper();

        List<OSProcess> processes = os.getProcesses();

        String json = null;
        for(OSProcess process : processes){
           // System.out.println(process);
            try{
                 json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(process);

            }catch(JsonProcessingException e){
                System.err.println("JSON处理错误: " + e.getMessage());
            }
            System.out.println(json);
            System.out.println("-----------------------------------------------------");

        }
        System.out.println("进程总数："+os.getProcessCount());
    }
}
